<?php
namespace control;
/*
*客户对账单类
*/

class clientReconciliationClass extends adIndexClass
{
    private const page = 'clientReconciliation';
    private const title = '客户对账单';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'targetDate'          => [
                        'name'  => "单据日期",
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'settlementType'  => [
                        'name'  => '结算方式',
                        'width' => 100,
                    ],
                    'period'         => [
                        'name'  => '结算期限',
                        'width' => 120,
                    ],
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'classify'          => [
                        'name'  => '业务类型',
                        'width' => 100,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 150,
                    ],
                    'name'          => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'num'          => [
                        'name'  => '数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'price'          => [
                        'name'  => '单价(' . static::$unit . ')',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 70,
                    ],
                    'saleMoney'          => [
                        'name'  => '销售金额(' . static::$unit . ')',
                        'width' => 150,
                    ],
                    'recMoney'          => [
                        'name'  => '实际收款金额(' . static::$unit . ')',
                        'width' => 150,
                    ],
                    'balance'          => [
                        'name'  => '应收款余额(' . static::$unit . ')',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 250,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $client = query('kehu',"coid = '" . self::$coid . "' order by orderNo,time asc");
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "客户" => clientProfileClass::kehuSelect(array('title' => '','value'=>$client['khid'])),
                    "单据日期"   => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    '备注' => text(array("name" => "text")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {

        //like查询数组
        $like = array(
            'text' =>$this->post('text'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
        );
        $and = " and typeId = '" . $this->post('khid') . "'";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'targetDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'targetDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => "record", "where" => $where, "order" => $orderBy['orderBy']));
        static::rSet(self::$stid.self::page.'Sql',$page['fullSql']);
        $inReceipt = new inReceiptClass();
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            if (in_array($array['classify'], ['核销', '收款单核销', '收款单'])) {
                $recMoney = $array['money'] !=0?-$array['money']:$array['money'];
                $saleMoney = 0;
            } else {
                $recMoney = 0;
                $saleMoney = $array['money'];
                $material = query('material',"id = '$array[materialId]'");
            }
            $settlementType = '';
            $period = '';
            if ($array['classify'] =='销售发货'){
                $saleSendOrder = query('sale_send_order',"orderNo = '$array[orderNo]' and coid = '".self::$coid."'");
                $settlementType = saleOrderClass::getPeriod($saleSendOrder['settlementType'],$saleSendOrder['settlementDay']);
                $period = $inReceipt->settlementPeriod($saleSendOrder['settlementType'],$saleSendOrder['recordDate'],$saleSendOrder['settlementDay']);
            }
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'settlementType':
                        $row[] = $settlementType;
                        break;
                    case 'period':
                        $row[] = $period;
                        break;
                    case 'code':
                    case 'name':
                    case 'model':
                        $row[] = isset($material[$key])&&$material[$key]?$material[$key]:'';
                        break;
                    case 'saleMoney':
                        $row[] = $saleMoney;
                        break;
                    case 'recMoney':
                        $row[] = $recMoney;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" .$page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = "您还没有导出的权限";
        }  else {
            $inReceipt = new inReceiptClass();
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array("table" => "record", "where" =>  "id in ('".implode("','", $checkedId)."') order by id desc"))['array'];
            }else{
                $sql = static::rGet(self::$stid.self::page.'Sql');
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $settlementType = '';
                $period = '';
                if (in_array($array['classify'],  ['核销', '收款单核销', '收款单'])) {
                    $recMoney = $array['money'];
                    $saleMoney = 0;
                } else {
                    $recMoney = 0;
                    $saleMoney = $array['money'];
                    $material = query('material',"id = '$array[materialId]'");
                }
                if ($array['classify'] =='销售发货'){
                    $saleSendOrder = query('sale_send_order',"orderNo = '$array[orderNo]' and coid = '".self::$coid."'");
                    $settlementType = saleOrderClass::getPeriod($saleSendOrder['settlementType'],$saleSendOrder['settlementDay']);
                    $period = $inReceipt->settlementPeriod($saleSendOrder['settlementType'],$saleSendOrder['recordDate'],$saleSendOrder['settlementDay']);
                }
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据日期'=>$array['targetDate'],
                            '结算方式'=>$settlementType,
                            '结算期限'=>$period,
                            '单据编号'=>$array['orderNo'],
                            '业务类型'=>$array['classify'],
                            '物料编码'=>$material['code']??'',
                            '物料名称'=>$material['name']??'',
                            '规格型号'=>$material['model']??'',
                            '数量'=>self::lostZero($array['num'],'numPrecision'),
                            '单价'=>$array['price'],
                            '单位'=>$array['unit'],
                            '销售金额'=>$saleMoney,
                            '实际收款金额'=>$recMoney,
                            '应收款余额'=>$array['balance'],
                            '备注'=>$array['text'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了客户对账单";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "客户对账单.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                ],
                [
                    'columnName'=>'结算方式',
                    'aliasName'=>'结算方式',
                ],
                [
                    'columnName'=>'结算期限',
                    'aliasName'=>'结算期限',
                ],
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'业务类型',
                    'aliasName'=>'业务类型',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'数量',
                    'aliasName'=>'数量',
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价(元)',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'销售金额',
                    'aliasName'=>'销售金额(元)',
                ],
                [
                    'columnName'=>'实际收款金额',
                    'aliasName'=>'实际收款金额(元)',
                ],
                [
                    'columnName'=>'应收款余额',
                    'aliasName'=>'应收款余额(元)',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
            ]
        };
    }
}

